import React, {useRef} from "react";
import {useTranslation} from 'react-i18next';
import classNames from "classnames";
import {showToast} from '@tools/utils'
import * as commonStyles from '@/index.less';
import './index.less';

const Clipboard = (props) => {
    const { text } = props;
    const textRef = useRef(null);
    const { t } = useTranslation();

    // 复制
    const handleCopy = async (e) => {
        const textarea = document.createElement('textarea');
        textarea.setAttribute('readonly', 'readonly');
        textarea.value = text;

        // 为了兼容
        try {
            await navigator.clipboard.writeText(textarea.value);
            showToast('复制成功')
        } catch (error) {
            try {
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                showToast('复制成功')
            } catch (error) {
                console.error('复制失败', error);
                showToast('复制失败')
            }
            document.body.removeChild(textarea);
        }
       
    }

    return (
        <div className="clipboard">
            <div className="clipboard__container">
                <div className="clipboard__container__text" ref={textRef} onClick={handleCopy}>
                <div className={`clipboard__container_tooltip tooltip_hover`} >
                    <div className="clipboard__container_tooltip_btn" >
                        {/* 点击可完成复制 */}
                        <span>{t('complete_copy')}</span>
                        <i className= {classNames(commonStyles.iconfont, 'copy_icon')}>&#xec7a;</i>
                    </div>
                </div>
                {text}
                </div>
            </div>
        </div>
    )
}

export default Clipboard;